<?php

namespace app\common\model\system;

use basic\BaseModel;
use traits\ModelTrait;

/**
 * 系统配置类
 * Class SystemConfig
 * @package app\common\model\system
 */
class SystemConfig extends BaseModel
{
    /**
     * 数据表的名称
     * @var string
     */
    protected $name = "system_config";

    /**
     * 主键
     * @var string
     */
    protected $pk = "id";

    use ModelTrait;

    /**
     * @title 修改单个配置
     * @param $menu
     * @param $value
     * @return bool
     */
    public static function setValue($menu, $value)
    {
        if (empty($menu) || !$config_one = self::get(["menu_name" => $menu])) return self::setErrorInfo("字段名称错误");
        if ($config_one["type"] == "radio" || $config_one["type"] == "checkbox") {
            $option = array();
            $parameter = explode(",", $config_one["parameter"]);
            foreach ($parameter as $k => $v) {
                if (isset($v) && !empty($v)) {
                    $option[$k] = explode("-", $v);
                }
            }
            $value_arr = array();   // 选项的值
            foreach ($option as $k => $v) {
                foreach ($v as $kk => $vv) {
                    if (!$vv) {
                        $value_arr[$k] = $vv;
                    }
                }
            }
            $i = 0;
            if (is_array($value)) {
                foreach ($value as $value_v) {
                    if (in_array($value_v, $value_arr)) {
                        $i++;
                    }
                    if (count($value) != $i) return self::setErrorInfo("输入的值不属于选项中的参数");
                }

            } else {
                if (in_array($value, $value_arr)) {
                    $i++;
                }
                if (!$i) return self::setErrorInfo("输入的值不属于选项中的参数");
            }
            if ($config_one["type"] == "radio" && is_array($value)) return self::setErrorInfo("单选框的值是字符串不是数组");
        }
        return self::edit(["value" => json_encode($value)], $menu, "menu_name");
    }


    /**
     * @title 获取单个配置
     * @param $menu
     * @return bool|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getConfigValue($menu)
    {
        if (empty($menu) || !($config_one = self::where("wxapp_id", self::$wxapp_id)->where(["menu_name", $menu])->find())) return false;
        return json_decode($config_one["value"], true);
    }

    /**
     * 获得多个参数
     * @param $menus
     * @return array
     */
    public static function getMore($menus)
    {
        $menus = is_array($menus) ? implode(',', $menus) : $menus;
        $list = self::where('menu_name', 'IN', $menus)->where("wxapp_id", self::$wxapp_id)->column('value', 'menu_name') ?: [];
        foreach ($list as $menu => $value) {
            $list[$menu] = json_decode($value, true);
        }
        return $list;
    }


    /**
     * @title 获取所有的配置
     */
    public static function getAllConfig()
    {
        $list = self::column("value", "menu_name") ?: [];
        foreach ($list as $menu => $value) {
            $list[$menu] = json_decode($value, true);
        }
        return $list;
    }

    /**
     * @title 判断
     * @param $data
     * @return bool
     */
    public static function valiDateTextRole($data)
    {
        if (!$data["width"]) return self::setErrorInfo("请输入文本框的宽度");
        if ($data["width"] <= 0) return self::setErrorInfo("请输入正确的文本框的宽度");
        return true;
    }

    /**
     * @title radio 和 checkbox 规则的判断
     * @param $data
     * @return bool
     */
    public static function valiDataRadioAndCheckbox($data)
    {
        $parameter = array();
        $option = array();
        $option_new = array();
        $data["parameter"] = str_replace("\r\n", "\n", $data["parameter"]); // 防止不兼容
        $parameter = explode("\n", $data["parameter"]);
        if (count($parameter) < 2) return self::setErrorInfo("请输入正确格式的配置参数");
        foreach ($parameter as $k => $v) {
            if (isset($v) && !empty($v)) {
                $option[$k] = explode("=>", $v);
            }
        }
        if (count($option) < 2) return self::setErrorInfo("请输入正确格式的配置参数");
        $bool = 1;
        foreach ($option as $k => $v) {
            $option_new[$k] = $option[$k][0];
            foreach ($v as $kk => $vv) {
                $vv_num = strlen($vv);
                if (!$vv_num) {
                    $bool = 0;
                }
            }
        }
        if (!$bool) return self::setErrorInfo('请输入正确格式的配置参数');
        $num1 = count($option_new);//提取该数组的数目
        $arr2 = array_unique($option_new);//合并相同的元素
        $num2 = count($arr2);//提取合并后数组个数
        if ($num1 > $num2) return self::setErrorInfo('请输入正确格式的配置参数');
        return true;
    }

    /**
     * @title 判断
     * @param $data
     * @return bool
     */
    public static function valiDateTextareaRole($data)
    {
        if (!$data["width"]) return self::setErrorInfo("请输入多行文本框的宽度");
        if (!$data['high']) return self::setErrorInfo('请输入多行文本框的高度');
        if ($data['width'] < 0) return self::setErrorInfo('请输入正确的多行文本框的宽度');
        if ($data['high'] < 0) return self::setErrorInfo('请输入正确的多行文本框的宽度');
        return true;
    }

    /**
     * @title 获取一个数据
     * @param $filed
     * @param $value
     * @return SystemConfig
     */
    public static function getOneConfig($filed, $value)
    {
        $where[$filed] = $value;
        return self::get($where);
    }

    /**
     * @title 获取配置分类
     * @param $id
     * @param int $status
     * @return \think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getAll($id, int $status = 1)
    {
        $where["config_table_id"] = $id;
        if ($status == 1) $where["status"] = $status;
        return self::where($where)->order("sort desc, id asc")->select();
    }

    /**
     * 获取所有配置分类
     * @param int $type
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getConfigTabAll($type = 0)
    {
        $configAll = SystemConfigTab::getAll($type);
        $config_tab = array();
        foreach ($configAll as $k => $v) {
            if (!$v["info"]) {
                $config_tab[$k]['value'] = $v['id'];
                $config_tab[$k]['label'] = $v['title'];
                $config_tab[$k]['icon'] = $v['icon'];
                $config_tab[$k]['type'] = $v['type'];
            }
        }
        return $config_tab;
    }

    /**
     * 选择类型
     * @param string $type
     * @return array
     */
    public static function radioType($type = 'text')
    {
        return [
            ['value' => 'text', 'label' => '文本框', 'disabled' => 1]
            , ['value' => 'textarea', 'label' => '多行文本框', 'disabled' => 1]
            , ['value' => 'radio', 'label' => '单选按钮', 'disabled' => 1]
            , ['value' => 'upload', 'label' => '文件上传', 'disabled' => 1]
            , ['value' => 'checkbox', 'label' => '多选按钮', 'disabled' => 1]
        ];
    }

    /**
     * 选择文本框类型
     * @param string $type
     * @return array
     */
    public static function textType($type = 'text')
    {
        return [
            ['value' => 'input', 'label' => '文本框']
            , ['value' => 'dateTime', 'label' => '时间']
            , ['value' => 'color', 'label' => '颜色']
            , ['value' => 'number', 'label' => '数字']
        ];
    }

    /**
     * 选择文文件类型
     * @param string $type
     * @return array
     */
    public static function uploadType($type = 'text')
    {
        return [['value' => 1, 'label' => '单图']
            , ['value' => 2, 'label' => '多图']
            , ['value' => 3, 'label' => '文件']];
    }

    /**
     * 字段状态
     * @param string $type
     * @return array
     */
    public static function formStatus($type = 'text')
    {
        return [['value' => 1, 'label' => '显示'], ['value' => 2, 'label' => '隐藏']];
    }

    /**
     * @title 文本框
     * @param $tab_id
     * @return array
     * @throws \FormBuilder\exception\FormBuilderException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function createInputRule($tab_id)
    {
        $formBuild = array();
        $formBuild[] = Form::hidden("type", "text");
        $formBuild[] = Form::select("config_tab_id", "分类", $tab_id)->setOptions(SystemConfig::getConfigTabAll(-1));
        $formBuild[] = Form::select('input_type', '类型')->setOptions(self::texttype());
        $formBuild[] = Form::input('info', '配置名称')->autofocus(1);
        $formBuild[] = Form::input('menu_name', '字段变量')->placeholder('例如：site_url');
        $formBuild[] = Form::input('desc', '配置简介');
        $formBuild[] = Form::input('value', '默认值');
        $formBuild[] = Form::number('width', '文本框宽(%)', 100);
        $formBuild[] = Form::input('required', '验证规则')->placeholder('多个请用,隔开例如：required:true,url:true');
        $formBuild[] = Form::number('sort', '排序');
        $formBuild[] = Form::radio('status', '状态', 1)->options(self::formstatus());
        return $formBuild;
    }

    /**
     * 多行文本框
     * @param $tab_id
     * @return array
     * @throws \FormBuilder\exception\FormBuilderException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function createTextAreaRule($tab_id)
    {
        $formBuild = array();
        $formBuild[] = Form::hidden('type', 'textarea');
        $formBuild[] = Form::select('config_tab_id', '分类', $tab_id)->setOptions(SystemConfig::getConfigTabAll(-1));
        $formBuild[] = Form::input('info', '配置名称')->autofocus(1);
        $formBuild[] = Form::input('menu_name', '字段变量')->placeholder('例如：site_url');
        $formBuild[] = Form::input('desc', '配置简介');
        $formBuild[] = Form::textarea('value', '默认值');
        $formBuild[] = Form::number('width', '文本框宽(%)', 100);
        $formBuild[] = Form::number('high', '多行文本框高(%)', 5);
        $formBuild[] = Form::number('sort', '排序');
        $formBuild[] = Form::radio('status', '状态', 1)->options(self::formstatus());
        return $formBuild;
    }

    /**
     * 单选按钮
     * @param $tab_id
     * @return array
     * @throws \FormBuilder\exception\FormBuilderException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function createRadioRule($tab_id)
    {
        $formBuild = array();
        $formBuild[] = Form::hidden('type', 'radio');
        $formBuild[] = Form::select('config_tab_id', '分类', $tab_id)->setOptions(SystemConfig::getConfigTabAll(-1));
        $formBuild[] = Form::input('info', '配置名称')->autofocus(1);
        $formBuild[] = Form::input('menu_name', '字段变量')->placeholder('例如：site_url');
        $formBuild[] = Form::input('desc', '配置简介');
        $formBuild[] = Form::textarea('parameter', '配置参数')->placeholder("参数方式例如:\n1=>男\n2=>女\n3=>保密");
        $formBuild[] = Form::input('value', '默认值');
        $formBuild[] = Form::number('sort', '排序');
        $formBuild[] = Form::radio('status', '状态', 1)->options(self::formstatus());
        return $formBuild;
    }

    /**
     * 文件上传
     * @param $tab_id
     * @return array
     * @throws \FormBuilder\exception\FormBuilderException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function createUploadRule($tab_id)
    {
        $formBuild = array();
        $formBuild[] = Form::hidden('type', 'upload');
        $formBuild[] = Form::select('config_tab_id', '分类', $tab_id)->setOptions(SystemConfig::getConfigTabAll(-1));
        $formBuild[] = Form::input('info', '配置名称')->autofocus(1);
        $formBuild[] = Form::input('menu_name', '字段变量')->placeholder('例如：site_url');
        $formBuild[] = Form::input('desc', '配置简介');
        $formBuild[] = Form::radio('upload_type', '上传类型', 1)->options(self::uploadtype());
        $formBuild[] = Form::number('sort', '排序');
        $formBuild[] = Form::radio('status', '状态', 1)->options(self::formstatus());
        return $formBuild;
    }

    /**
     * 多选框
     * @param $tab_id
     * @return array
     * @throws \FormBuilder\exception\FormBuilderException
     */
    public static function createCheckboxRule($tab_id)
    {
        $formBuild = array();
        $formBuild[] = Form::hidden('type', 'checkbox');
        $formBuild[] = Form::select('config_tab_id', '分类', $tab_id)->setOptions(SystemConfig::getConfigTabAll(-1));
        $formBuild[] = Form::input('info', '配置名称')->autofocus(1);
        $formBuild[] = Form::input('menu_name', '字段变量')->placeholder('例如：site_url');
        $formBuild[] = Form::input('desc', '配置简介');
        $formBuild[] = Form::textarea('parameter', '配置参数')->placeholder("参数方式例如:\n1=>白色\n2=>红色\n3=>黑色");
        // $formBuild[] = Form::input('value','默认值');
        $formBuild[] = Form::number('sort', '排序');
        $formBuild[] = Form::radio('status', '状态', 1)->options(self::formstatus());
        return $formBuild;
    }

    /**
     * 下拉框
     * @param $tab_id
     * @return array
     * @throws \FormBuilder\exception\FormBuilderException
     */
    public static function createSelectRule($tab_id)
    {
        $formBuild = array();
        $formBuild[] = Form::hidden('type', 'select');
        $formBuild[] = Form::select('config_tab_id', '分类', $tab_id)->setOptions(SystemConfig::getConfigTabAll(-1));
        $formBuild[] = Form::input('info', '配置名称')->autofocus(1);
        $formBuild[] = Form::input('menu_name', '字段变量')->placeholder('例如：site_url');
        $formBuild[] = Form::input('desc', '配置简介');
        $formBuild[] = Form::textarea('parameter', '配置参数')->placeholder("参数方式例如:\n1=>白色\n2=>红色\n3=>黑色");
        // $formBuild[] = Form::input('value','默认值');
        $formBuild[] = Form::number('sort', '排序');
        $formBuild[] = Form::radio('status', '状态', 1)->options(self::formstatus());
        return $formBuild;
    }

    /**
     * 配置短信信息
     * @param $account
     * @param $token
     * @return bool
     */
    public static function setConfigSmsInfo($account, $token)
    {
        self::beginTrans();
        $res1 = self::where('menu_name', 'sms_account')->where('value', '"' . $account . '"')->count();
        if (!$res1) $res1 = self::where('menu_name', 'sms_account')->update(['value' => '"' . $account . '"']);
        $res2 = self::where('menu_name', 'sms_token')->where('value', '"' . $token . '"')->count();
        if (!$res2) $res2 = self::where('menu_name', 'sms_token')->update(['value' => '"' . $token . '"']);
        $res = $res1 && $res2;
        self::checkTrans($res);
        return $res;
    }
}